import React, { useEffect,useState } from 'react';
import {
  Drawer,
  Steps,
  Button,
  Space,
  Divider,
  message,
  Form
} from 'antd';
import {
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormDigit,
  ProFormRadio,
} from '@ant-design/pro-components';
import { PlusOutlined ,MinusCircleOutlined} from '@ant-design/icons';
import TreeSelectDropdown from '../components/TreeSelectDropdown';
import { useIntl } from '@umijs/max';

const { Step } = Steps;

interface AddAccountDrawerProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const AddProductDrawer: React.FC<AddAccountDrawerProps> = ({
  visible,
  onClose,
  onSuccess,
}) => {
  const intl = useIntl();

  const [form] = ProForm.useForm();
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);

  const [basefeeRules, setBasefeeRules] = useState([]);

  useEffect(() => {
    const fetchFeeOptions = async () => {
      await initBaseFeeRule();
    };
    fetchFeeOptions();
  }, []); 

  const initBaseFeeRule = async () => {
    // try {
    //   // Replace with your actual API endpoint
    //   const response = await fetch('/api/logistics/fee-rules');
    //   const data = await response.json();
    //   // Transform the data into the format ProFormSelect expects
    //   const options = data.map(item => ({
    //     label: item.name,  // Display text
    //     value: item.code   // Actual value stored in form
    //   }));

    //   setBasefeeRules(options);
    // } catch (error) {
    //   console.error('Failed to fetch fee options:', error);
    //   // You might want to set some default options or show an error message
    //   setBasefeeRules([]);
    // }
  }

  const resetForm = () => {
    form.resetFields();
    setCurrentStep(0);
  };
  const handleCancel = () => {
    resetForm();
    onClose();
  };
  const steps = [
    {
      title: intl.formatMessage({ id: "pages.product.step.basic" }),
      fields: ["pCode", "pName", "pStatus", "remask", "sp"],
      content: (
        <>
          <ProFormText
            name="pCode"
            label={intl.formatMessage({ id: "pages.product.code" })}
            placeholder={intl.formatMessage({
              id: "pages.product.code.placeholder",
            })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: "pages.product.code.required",
                }),
              },
            ]}
          />
          <ProFormText
            name="pName"
            label={intl.formatMessage({ id: "pages.product.name" })}
            placeholder={intl.formatMessage({
              id: "pages.product.name.placeholder",
            })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: "pages.product.name.required",
                }),
              },
            ]}
          />
          <TreeSelectDropdown
            name="sp"
            label={intl.formatMessage({ id: "pages.product.supplier" })}
            placeholder={intl.formatMessage({
              id: "pages.product.supplier.placeholder",
            })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: "pages.product.supplier.required",
                }),
              },
            ]}
          />
          <ProFormRadio.Group
            name="asStatus"
            label={intl.formatMessage({ id: "pages.product.status" })}
            rules={[{ required: true }]}
            initialValue="1"
            options={[
              {
                label: intl.formatMessage({ id: "pages.active" }),
                value: "0",
              },
              {
                label: intl.formatMessage({ id: "pages.inactive" }),
                value: "1",
              },
            ]}
          />
          <ProFormTextArea
            name="remask"
            label={intl.formatMessage({ id: "pages.product.remark" })}
            placeholder=""
            fieldProps={{ rows: 4 }}
          />
        </>
      ),
    },
    {
      title: intl.formatMessage({ id: "pages.product.step.feeRule" }),
      fields: ["base_trading_fee", "extra_trading_fees"],
      content: (
        <>
          <div style={{ marginTop: 24 }}>
            <h4>{intl.formatMessage({ id: "pages.product.baseFeeRule" })}</h4>
            <ProForm.Item name="base_trading_fee" noStyle>
              <Space
                align="baseline"
                style={{ display: "flex", marginBottom: 8, width: "100%" }}
              >
                <ProFormSelect
                  name="fee"
                  label={intl.formatMessage({
                    id: "pages.product.feeRuleName",
                  })}
                  placeholder={intl.formatMessage({
                    id: "pages.product.feeRuleName.placeholder",
                  })}
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({
                        id: "pages.product.feeRuleName.required",
                      }),
                    },
                  ]}
                  fieldProps={{ style: { width: 180 } }}
                  options={basefeeRules}
                />
                <div style={{ flex: 1 }} />
                <ProFormText
                  name="rule_code"
                  label={intl.formatMessage({ id: "pages.product.ruleCode" })}
                  placeholder={intl.formatMessage({
                    id: "pages.product.ruleCode",
                  })}
                  fieldProps={{ style: { width: 180 }, readOnly: true }}
                />
                <div style={{ flex: 1 }} />
                <ProFormText
                  name="calc_type"
                  label={intl.formatMessage({ id: "pages.product.calcType" })}
                  placeholder={intl.formatMessage({
                    id: "pages.product.calcType",
                  })}
                  fieldProps={{ style: { width: 180 }, readOnly: true }}
                />
                <div style={{ flex: 1 }} />
                <ProFormText
                  name="rule_value"
                  label={intl.formatMessage({ id: "pages.product.ruleValue" })}
                  placeholder={intl.formatMessage({
                    id: "pages.product.ruleValue",
                  })}
                  fieldProps={{ style: { width: 180 }, readOnly: true }}
                />
                <div style={{ flex: 1 }} />
                <ProFormText
                  name="description"
                  label={intl.formatMessage({
                    id: "pages.product.description",
                  })}
                  placeholder={intl.formatMessage({
                    id: "pages.product.description",
                  })}
                  fieldProps={{ style: { width: 250 }, readOnly: true }}
                />
              </Space>
            </ProForm.Item>
          </div>
          <div style={{ marginTop: 24 }}>
            <h4>{intl.formatMessage({ id: "pages.product.extraFeeRule" })}</h4>
            <Form.List name="extra_trading_fees">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space
                      key={key}
                      style={{ display: "flex", marginBottom: 8 }}
                      align="baseline"
                    >
                      <ProFormDigit
                        {...restField}
                        name={[name, "fee"]}
                        label={intl.formatMessage({
                          id: "pages.product.extraFee",
                        })}
                        placeholder={intl.formatMessage({
                          id: "pages.product.extraFee.placeholder",
                        })}
                        rules={[
                          {
                            required: true,
                            message: intl.formatMessage({
                              id: "pages.product.extraFee.required",
                            }),
                          },
                        ]}
                        min={0}
                        max={100}
                        precision={4}
                        fieldProps={{ style: { width: "100%" } }}
                      />
                      <ProFormText
                        {...restField}
                        name={[name, "rule_code"]}
                        label={intl.formatMessage({
                          id: "pages.product.ruleCode",
                        })}
                        fieldProps={{ style: { width: "100%" } }}
                      />
                      <ProFormText
                        {...restField}
                        name={[name, "calc_type"]}
                        label={intl.formatMessage({
                          id: "pages.product.calcType",
                        })}
                        fieldProps={{ style: { width: "100%" } }}
                      />
                      <ProFormText
                        {...restField}
                        name={[name, "rule_value"]}
                        label={intl.formatMessage({
                          id: "pages.product.ruleValue",
                        })}
                        fieldProps={{ style: { width: "100%" } }}
                      />
                      <ProFormText
                        {...restField}
                        name={[name, "description"]}
                        label={intl.formatMessage({
                          id: "pages.product.description",
                        })}
                        fieldProps={{ style: { width: "100%" } }}
                      />
                      <MinusCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  ))}
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => add()}
                      block
                      icon={<PlusOutlined />}
                    >
                      {intl.formatMessage({
                        id: "pages.product.addExtraFeeRule",
                      })}
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </div>
        </>
      ),
    },
    {
      title: intl.formatMessage({ id: "pages.product.step.other" }),
      fields: ["extra_params"],
      content: (
        <ProFormTextArea
          name="extra_params"
          label={intl.formatMessage({ id: "pages.product.extraParams" })}
          placeholder={intl.formatMessage({
            id: "pages.product.extraParams.placeholder",
          })}
          fieldProps={{ rows: 4 }}
        />
      ),
    },
  ];

  const next = () => {
    const currentFields = steps[currentStep].fields;
    form.validateFields(currentFields)
      .then(() => {
        setCurrentStep(currentStep + 1);
      })
      .catch((err) => {
        console.log('Validation Error:', err);
      });
  };

  const prev = () => {
    setCurrentStep(currentStep - 1);
  };

  const handleSubmit = async () => {
    try {
      setLoading(true);
      const allFields = steps.flatMap(step => step.fields);
      const values = await form.validateFields(allFields);
      console.log(values)
      onSuccess();
       message.success(intl.formatMessage({ id: 'pages.account.add.success' }));
      form.resetFields();
      resetForm();
      setCurrentStep(0);
      onClose();
    } catch (error) {
     message.error(intl.formatMessage({ id: 'pages.account.add.error' }));
    } finally {
      setLoading(false);
    }
  };
  const isLastStep = currentStep === steps.length - 1;

  return (
    <Drawer
      title={intl.formatMessage({ id: "pages.product.add.title" })}
      width={1100}
      onClose={onClose}
      open={visible}
      bodyStyle={{ paddingBottom: 80 }}
      extra={
        <Space>
          <Button onClick={handleCancel}>
            {intl.formatMessage({ id: "pages.cancel" })}
          </Button>
        </Space>
      }
    >
      <Steps current={currentStep} style={{ marginBottom: 24 }}>
        {steps.map((item) => (
          <Step
            key={item.title}
            title={intl.formatMessage({ id: `pages.product.step.${item.key}` })}
          />
        ))}
      </Steps>

      <ProForm
        form={form}
        layout="vertical"
        submitter={false}
        initialValues={{
          dataset_env: "production",
          trading_fee: 0.1,
        }}
      >
        <div>{steps[currentStep].content}</div>
      </ProForm>

      <Divider />

      <div style={{ textAlign: "right", marginTop: 24 }}>
        {currentStep > 0 && (
          <Button style={{ marginRight: 8 }} onClick={prev}>
            {intl.formatMessage({ id: "pages.previous" })}
          </Button>
        )}
        {!isLastStep ? (
          <Button type="primary" onClick={next}>
            {intl.formatMessage({ id: "pages.next" })}
          </Button>
        ) : (
          <Button
            type="primary"
            onClick={handleSubmit}
            loading={loading}
            icon={<PlusOutlined />}
          >
            {intl.formatMessage({ id: "pages.submit" })}
          </Button>
        )}
      </div>
    </Drawer>
  );
};

export default AddProductDrawer;